package com.kuang.demo02;

/**测试死锁
 * 死锁：
 *  两个或者多个对象互相拿着对方想要的资源，
 *  从而形成了僵持的局面
 * @author FHL
 */
public class TestMirror {
    public static void main(String[] args) {
        Makeup girl1=new Makeup(0,"依依");
        Makeup girl2=new Makeup(1,"Licy");
            girl1.start();
            girl2.start();
    }
}
//口红
class Lipstick{

}
//镜子
class Mirror{

}
class Makeup extends Thread{
    //让需要的资源只有一份（用static来修饰使其只有独一份）
    static Lipstick lipstick=new Lipstick();
    static Mirror mirror=new Mirror();
    //选择
    int choice;
    //化妆者
    String name;
    Makeup(int choice,String name){
        this.choice=choice;
        this.name=name;
    }
    @Override
    public void run() {
//化妆
        makeup();

    }
    //化妆。两个对象分别持有一个锁，都想要对方手里的那个锁
    public void makeup() {
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.name + "获得口红的锁！");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //1秒钟后想要获得镜子的锁
            synchronized (mirror) {
                System.out.println(this.name + "获得镜子的锁。。。。。。");
            }
            }else{
            synchronized (mirror) {
                System.out.println(this.name + "获得镜子的锁！");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        //3秒钟后想要获得口红的锁
        synchronized (lipstick) {
            System.out.println(this.name + "获得口红的锁。。。。。。");
        }
    }
        }

    }


